package com.project.lk.nurseapp.sphy;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.base.UrlContants;
import com.project.lk.nurseapp.common.adapter.TypeItemAdapter;
import com.project.lk.nurseapp.common.bean.TypeItemBean;
import com.project.lk.nurseapp.common.view.bluetooth.BleManager;
import com.project.lk.nurseapp.common.view.bluetooth.BluetoothListActivity;
import com.project.lk.nurseapp.common.view.bluetooth.StarConstants;
import com.project.lk.nurseapp.inputfiles.InputSphyActivity;
import com.project.lk.nurseapp.sphy.presenter.IPostSphyView;
import com.project.lk.nurseapp.sphy.presenter.PostSphyPresenter;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.ByteToStringUtils;
import com.project.lk.nurseapp.utils.PopWindowManager;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.TimeUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.project.lk.nurseapp.utils.TypeUtils;
import com.project.lk.nurseapp.utils.UserInfoUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.project.lk.nurseapp.common.view.bluetooth.StarConstants.NEW_SPHY_READ_ID;
import static com.project.lk.nurseapp.common.view.bluetooth.StarConstants.NEW_SPHY_SERVICE_ID;
import static com.project.lk.nurseapp.common.view.bluetooth.StarConstants.NEW_SPHY_WEITE_ID;
import static com.project.lk.nurseapp.common.view.bluetooth.StarConstants.sphy_code_begin;
/**
 * 功能介绍：蓝牙模块方法调用基本一样，血压计测量界面
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class SphyActivity extends BaseActivity implements IPostSphyView {


    @BindView(R.id.hint_tv)
    TextView hintTv;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.shrink_num_tv)
    TextView shrinkNumTv;
    @BindView(R.id.diastole_num_tv)
    TextView diastoleNumTv;
    @BindView(R.id.pulse_num_tv)
    TextView pulseNumTv;
    @BindView(R.id.type_recyclerview)
    RecyclerView typeRecyclerview;
    @BindView(R.id.record_recyclerview)
    RecyclerView recordRecyclerview;
    @BindView(R.id.sphy_chart)
    LineChart sphyChart;
    private BleManager bleManager;
    private View praentView;
    private View blueContentView;
    private PopupWindow bluePopupWindow;
    private boolean has;
    private String mdata;
    private TypeItemAdapter typeAdapter;
    private List<TypeItemBean> typeItemBeanList;
    private String mcode;
    private boolean hascode;
    private boolean mea;
    private String login = "";
    private PostSphyPresenter presenter;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void initData() {
        login = getIntent().getStringExtra("login");
        if (TextUtils.equals(login, "login")) {
            presenter = new PostSphyPresenter(this);
        }
        /*初始化蓝牙模块*/
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bleManager = BleManager.init();
        bleManager.initialize();
    }

    @Override
    protected void initView() {

        typeItemBeanList = new ArrayList<>();
        for (int i = 0; i < typeStr.length; i++) {
            TypeItemBean typeItemBean = new TypeItemBean();
            typeItemBean.setColor(typeColor[i]);
            typeItemBean.setSelect(false);
            typeItemBean.setTitle(typeStr[i]);
            typeItemBeanList.add(typeItemBean);
        }
        typeAdapter = new TypeItemAdapter(typeItemBeanList, this);
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(typeStr.length, StaggeredGridLayoutManager.VERTICAL);
        typeRecyclerview.setAdapter(typeAdapter);
        typeRecyclerview.setLayoutManager(manager);
        setBluetoothPopwind();
        YData.clear();
        YData.add(0);
        setLineChart(); //设置默认数据
    }

    int[] typeColor = new int[]{
            R.color.blue, R.color.green, R.color.little_green,
            R.color.little_yellow, R.color.yellow, R.color.orange,
            R.color.red};
    String[] typeStr = new String[]{"偏低", "理想", "正常", "偏高", "轻度", "中度", "重度"};


    @Override
    protected int getLayoutId() {
        return R.layout.activity_sphy;
    }

    private BluetoothAdapter mBluetoothAdapter;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @OnClick({R.id.back, R.id.start_test_but,R.id.input_but ,R.id.record_tv, R.id.hint_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.start_test_but: //开始测量

                if (TextUtils.equals(hintTv.getText(), "未连接")) {
                    startActivity(new Intent(this, BluetoothListActivity.class));
                } else { //开始测量
                    //发送开始
                    if (!isMeasure) {

                        //发送16进制的字节数组，响应蓝牙设备
                        boolean isNewSphy = (boolean) SharedPreferencesUtils.getParam("NewSphy", false);
                        if (isNewSphy) {
                            bleManager.sendByte(ByteToStringUtils.hexStringToByteArray(StarConstants.CMD_START),NEW_SPHY_SERVICE_ID,NEW_SPHY_WEITE_ID,NEW_SPHY_READ_ID);
                        }else {
                            bleManager.sendByte(ByteToStringUtils.hexStringToByteArray(sphy_code_begin));
                        }

                    } else {
                        ToastUtils.showShortToast("正在测量中，请勿再次测量");
                    }

                }

                break;
            case R.id.input_but: //手动录入
                startActivity(new Intent(this,InputSphyActivity.class));

                break;
            case R.id.record_tv: //历史记录
                startActivity(new Intent(this,SphyHistoryActivity.class));
                break;
            case R.id.hint_tv: //未连接
                if (hintTv.getText().equals("未连接")) {

                    PopWindowManager.showAsLocationWindow(praentView, blueContentView, bluePopupWindow, R.id.bluetooth_popwind_layout);
                }
                break;
        }
    }

    //设置弹窗
    private void setBluetoothPopwind() {
        praentView = LayoutInflater.from(this).inflate(R.layout.activity_msg_list, null);
        blueContentView = LayoutInflater.from(this).inflate(R.layout.bluetooth_popwind_layout, null);
        bluePopupWindow = new PopupWindow(blueContentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

        Button cancelBut = (Button) blueContentView.findViewById(R.id.cancel_but);
        Button commentBut = (Button) blueContentView.findViewById(R.id.setting_but);

        //点击事件
        setEvent(cancelBut, commentBut, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.cancel_but: //取消
                        bluePopupWindow.dismiss();
                        break;
                    case R.id.setting_but:  //设置
                        bluePopupWindow.dismiss();
                        startActivity(new Intent(SphyActivity.this, BluetoothListActivity.class));
                        break;
                }

            }
        });
    }

    //设置点击事件
    private void setEvent(Button cancelBut, Button commentBut, View.OnClickListener listener) {
        cancelBut.setOnClickListener(listener);
        commentBut.setOnClickListener(listener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Boolean isConn = (Boolean) SharedPreferencesUtils.getParam("Sphy", false);
        if (isConn && bleManager.isOpenBleTooth()) {
            hintTv.setText("已连接");
        } else {
            hintTv.setText("未连接");
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());


    }

    List<Integer> YData = new ArrayList<>();

    //画图
    private void setLineChart() {

        List<Entry> entries = new ArrayList<Entry>();
        for (int i = 0; i < YData.size(); i++) {
            entries.add(new Entry(i, YData.get(i)));
        }
        LineDataSet dataSet = new LineDataSet(entries, "气压表"); // add entries to dataset
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);
        LineData lineData = new LineData(dataSet);
        if (lineData != null) {
            sphyChart.setData(lineData);

        }
        sphyChart.getDescription().setEnabled(false);
        sphyChart.invalidate(); // refresh
        //获取右边的轴线
        YAxis rightAxis=sphyChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        XAxis xAxis = sphyChart.getXAxis();
        xAxis.setEnabled(true);//设置轴启用或禁用 如果禁用以下的设置全部不生效
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
    }

    /*注册广播*/
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleManager.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleManager.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    boolean isMeasure = false;
    int index = 0;
    /*测量结果回调广播*/
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BleManager.ACTION_GATT_CONNECTED.equals(action)) {
                Log.e("MLOG", "ACTION_GATT_CONNECTED");
            } else if (BleManager.ACTION_GATT_DISCONNECTED.equals(action)) {
                Log.e("MLOG", "ACTION_GATT_DISCONNECTED");
                SharedPreferencesUtils.setParam("Sphy", false);
                hintTv.setText("未连接");
            } else if (BleManager.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) { //连接成功后的回调
                List<BluetoothGattService> supportedGattServices = bleManager.getSupportedGattServices();
                showList(supportedGattServices);
                infoBluetooth();
                boolean isNewSphy = (boolean) SharedPreferencesUtils.getParam("NewSphy", false);
                if (isNewSphy) {
                    bleManager.initNotify(NEW_SPHY_SERVICE_ID,NEW_SPHY_READ_ID,NEW_SPHY_READ_ID);
                }else {
                    bleManager.initNotify();/*刷新通知，从而获取ble传来的数据*/
                }
                hintTv.setText("已连接");
            } else if (BleManager.ACTION_DATA_AVAILABLE.equals(action)) {  //数据返回回调
                if (intent.getStringExtra(BleManager.EXTRA_DATA) != null) {
                    Log.e("MLOG", intent.getStringExtra(BleManager.EXTRA_DATA));
                    String codeSphy = intent.getStringExtra(BleManager.EXTRA_DATA);
                    String[] splitSphy = codeSphy.split(" ");
                    index++;
                    if (index == 6) {
                        YData.clear();
                        YData.add(0);
                        isMeasure = true;
                        setLineChart();
                    }
                    boolean isNewSphy = (boolean) SharedPreferencesUtils.getParam("NewSphy", false);
                    if (isNewSphy) { //鹿得血压计测量前面第一个是序号
                        Log.e("MLOG",">>>>>>>>>>>>>>>>>>>");
                        sphyType(2,splitSphy,codeSphy);
                        showNewValue(splitSphy, codeSphy);
                    } else {  //家康血压计前面没有序号
                        sphyType(1,splitSphy,codeSphy);
                        showJiaValue(splitSphy, codeSphy);
                    }

                }

            }
        }
    };

    //F4 FE 83 01 00 00 04
    public void sphyType(int typeIndex,String[] splitSphy,String codeSphy){
        drawData(splitSphy,typeIndex);
        if (splitSphy.length <= 7) {
            if (codeSphy.contains("83")) {
                if (TextUtils.equals(splitSphy[typeIndex], "83")) {
                    if (splitSphy.length != 2) {
                        TypeUtils.showSphyErro(splitSphy[typeIndex+1]);
                    } else {
                        ToastUtils.showShortToast("量测失败，请重新量测");
                    }
                } else {
                    TypeUtils.showSphyErro(splitSphy[typeIndex]);  //测量失败返回类型
                }
                isMeasure = false;
            }
        }

    }
    //画表
    public void drawData(String[] splitSphy,int typeIndex) {
        if (splitSphy.length == 6||splitSphy.length==7) {
            switch (splitSphy[typeIndex]) {
                case "84":  //画表
                    String pressureH = ByteToStringUtils.hex16StrTo10Str(splitSphy[typeIndex+1]);
                    String pressureL = ByteToStringUtils.hex16StrTo10Str(splitSphy[typeIndex+2]);
                    Integer pressure = Integer.parseInt(pressureH) * 256 + Integer.parseInt(pressureL);
                    YData.add(pressure);
                    break;
                case "85":
                    ToastUtils.showShortToast("电池电量不足，测量失败");
                    isMeasure = false;
                    break;
            }
        }
    }
    //新血压计设置数据
    public void showNewValue(String[] mdata, String codeSphy){
        setLineChart();
        timeTv.setText(TimeUtils.getSateTime(new Date()));
        if (mdata.length>=5) {
            if (TextUtils.equals(mdata[1],"81")) {
                setDate(0,mdata);
            }
        }

    }
    //测量出家康血压计数据，并画图
    private void showJiaValue(String[] mdata, String codeSphy) {
        String hightStr = "";
        String shortStr = "";
        String pulseStr = "";
        int position = 0;
        setLineChart();
        timeTv.setText(TimeUtils.getSateTime(new Date()));
        if (codeSphy.contains("FF") && mdata[mdata.length - 1].equals("FF")
                && mdata.length < 8 && !codeSphy.contains("0C")
                && !codeSphy.contains("02") && !codeSphy.contains("03") && !codeSphy.contains("04")) {
            Log.e("MLOG", codeSphy + ">>>>>>>");
            isMeasure = true;
            return;
        }
        if (mdata.length > 8) {
            for (int i = 0; i < mdata.length; i++) {
                if (TextUtils.equals(mdata[i], "0C")) { //根据蓝牙提供的16进制进行取血压值
                    if (i + 4 < mdata.length) {
                        setDate(i,mdata); //设置数据
                    }
                }
            }
        }
    }
    //设置数据
    public void setDate(int i,String[] mdata){
     String   hightStr = ByteToStringUtils.hex16StrTo10Str(mdata[i + 2]);
        String   shortStr = ByteToStringUtils.hex16StrTo10Str(mdata[i + 3]);
        String   pulseStr = ByteToStringUtils.hex16StrTo10Str(mdata[i + 4]);
        Log.e("MLOG", "高压" + hightStr);
        Log.e("MLOG", "低压" + shortStr);
        Log.e("MLOG", "脉搏" + pulseStr);
        isMeasure = false;
        shrinkNumTv.setText(hightStr);
        diastoleNumTv.setText(shortStr);
        pulseNumTv.setText(pulseStr);
        if (!TextUtils.equals(hightStr, "") && !TextUtils.equals(shortStr, "")) {
            int sphyType = TypeUtils.getSphyType(hightStr, shortStr);
            for (int n = 0; n < typeItemBeanList.size(); n++) {
                typeItemBeanList.get(n).setSelect(false);
            }
            typeItemBeanList.get(sphyType).setSelect(true);
            typeAdapter.setTypeList(typeItemBeanList);
            typeAdapter.notifyDataSetChanged();
            index = 0;
            if (presenter != null) { //TODO:上传血压数据
                presenter.postSphtDate(new UserInfoUtils().getHealthUrl() + UrlContants.POST_SPHY_URL
                        , hightStr, shortStr, pulseStr, TypeUtils.getSphyTypeStr(hightStr, shortStr),
                        TimeUtils.getSateTime(new Date()));
            }


        }
    }

    List<BluetoothGattCharacteristic> mBluetoothList = new ArrayList<>();

    /*获取当前蓝牙服务设备的集合*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void showList(List<BluetoothGattService> gattServices) {
        for (BluetoothGattService gattService : gattServices) {
            List<BluetoothGattCharacteristic> gattCharacteristics =
                    gattService.getCharacteristics();
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                mBluetoothList.add(gattCharacteristic);
            }
        }
    }

    /*利用遍历蓝牙服务集合进行设置蓝牙可读可写 TODO：一定要加不然接收不到数据和写不了数据*/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void infoBluetooth() {
        for (BluetoothGattCharacteristic characteristic : mBluetoothList) {
            bleManager.setCharacteristicNotification(
                    characteristic, false);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bleManager != null) {
            bleManager.disableBlueBle("Sphy");  //关闭蓝牙，减少不必要的消耗和节省内存
        }
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        if (presenter != null) {
            presenter.dettachView();
            presenter = null;
        }
    }

    @Override
    public void postSuccess() {

    }

    @Override
    public void postFail() {

    }
}
